StartPage.MostPopular=(function(){return{
	items: null
	
	,populate: function(){
		if (!this.items){ this.refresh(); return; }
		var container=$('#most-visited', gBrowser.contentDocument);
		container.html(this.items.join(''))
	}
	
	,getIcon: function(aURI){
		var favSvc = Cc["@mozilla.org/browser/favicon-service;1"].getService(Ci.nsIFaviconService), icon; 
		if (!aURI) icon=favSvc.defaultFavicon.spec;
		else {
			icon = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newURI(aURI,null,null);
			if (icon) icon=favSvc.getFaviconLinkForIcon(icon).spec;
			else icon=aURI;
		}
		return icon;
	}
	
	,refresh: function(){
		var id, title, url, icon, frq, items=[], db, sql
		if (Ci.nsPIPlacesDatabase) db = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsPIPlacesDatabase).DBConnection;
		sql = db.createStatement(
			' SELECT DISTINCT moz_places.id, moz_places.title, moz_places.url, moz_favicons.url FROM moz_places '+
			' LEFT JOIN moz_favicons ON moz_places.favicon_id=moz_favicons.id'+
			' WHERE moz_places.visit_count>0 GROUP BY moz_places.title ORDER BY moz_places.frecency DESC LIMIT 0,10'
		);

		while(sql.executeStep()){
			id = sql.getString(0);
			title = sql.getString(1);
			url = sql.getString(2);
			icon = this.getIcon(sql.getString(3));
			del='<span title="Remove from list" class="del" id="plc'+id+'" onclick="fireEvent(\'removePlace\',this);return false"></span>';
			items.push('<li>'+del+'<a href="'+url+'"><img src="'+icon+'" />'+title+'</a>'+'</li>');			
		}
      sql.reset(); sql.finalize(); // Close the query incase there's more pages than we can show
		if (items.length) this.items=items;
		this.populate();
	}
}}());
